package com.ase.交替打印FooBar;

/**
 * @author gyhstart
 * @create 2021/2/19 - 18:33
 **/
public class Solution {
    public static void main(String[] args) {
        FooBar fooBar = new FooBar(2);
        new Thread(()-> {
            try {
                fooBar.foo(()-> System.out.print("foo"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        new Thread(()-> {
            try {
                fooBar.bar(()-> System.out.print("bar"));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    static class FooBar {
        private int n;

        //标记flag位为false，先执行foo
        private volatile boolean flag = false;

        public FooBar(int n) {
            this.n = n;
        }
        public synchronized void foo(Runnable printFoo) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                if (flag) {
                    this.wait();
                }
                printFoo.run();
                flag = true;
                this.notify();
            }
        }
        public synchronized void bar(Runnable printBar) throws InterruptedException {
            for (int i = 0; i < n; i++) {
                if (!flag) {
                    this.wait();
                }
                printBar.run();
                flag = false;
                this.notify();
            }
        }

    }
}
